<template>
  <div class="app-container">
    <el-row
      type="flex"
      class="row"
      style="height: 100%"
      justify="space-between"
      :gutter="12"
    >
      <el-col :span="6" style="height: 100%">
        <el-card class="card-wrap">
          <template #header>
            <el-row
              :gutter="10"
              type="flex"
              justify="space-between"
              align="middle"
            >
              <el-col :span="12">
                <span>元产品列表</span>
              </el-col>
              <el-col :span="12">
                <el-input
                  size="small"
                  v-model="keyword"
                  placeholder="输入关键词搜索"
                  clearable
                ></el-input>
              </el-col>
            </el-row>
          </template>
          <el-tree
            ref="metaTreeRef"
            :data="searchList"
            :props="{ label: 'metaName' }"
            :expand-on-click-node="false"
            default-expand-all
            node-key="id"
            show-checkbox
            check-on-click-node
            @check-change="handleMetaTreeCheckChange"
          />
        </el-card>
      </el-col>
      <el-col :span="18" style="height: 100%">
        <el-card header="排序与设置" class="card-wrap">
          <meta-sort :list="selectedMetaList" @delete-item="handleDeleteMeta" />
          <el-button
            style="margin-top: 16px"
            type="primary"
            size="medium"
            @click="handleSave"
            >提交</el-button
          >
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { fetchMetaList, fetchSkuMeta } from "@/api/product";
import MetaSort from "@/views/pms/sku/components/MetaSort.vue";
import { PAGE_SIZE_ALL } from "@/utils/constant/system";

export default {
  components: { MetaSort },
  props: {
    value: Array,
    id: {
      type: String,
    },
  },
  data() {
    return {
      metaList: [],
      selectedMetaList: [],
      keyword: "",
    };
  },
  computed: {
    searchList() {
      return this.keyword
        ? this.metaList.filter(this.createFilter(this.keyword))
        : this.metaList;
    },
  },

  created() {
    this.getMetaList();
  },

  methods: {
    getSelectedObjFromMetaList(obj) {
      const {
        metaId,
        metaName,
        metaType,
        num = 0,
        usePeriodDay = 0,
        waitingPeriodDay = 0,
        waitingPeriodRemark = null,
      } = obj;
      return {
        metaId,
        metaName,
        metaType,
        num,
        usePeriodDay,
        waitingPeriodDay,
        waitingPeriodRemark,
      };
    },
    getMetaDetail() {
      this.selectedMetaList = [];
      fetchSkuMeta(this.id).then((response) => {
        response.data.forEach((item) => {
          this.selectedMetaList.push(this.getSelectedObjFromMetaList(item));
        });
        this.$refs.metaTreeRef.setCheckedKeys(
          this.selectedMetaList.map((item) => item.metaId),
        );
      });
    },
    createFilter(queryString) {
      return (meta) => {
        return (
          meta.metaName.toLowerCase().indexOf(queryString.toLowerCase()) === 0
        );
      };
    },

    getMetaList() {
      fetchMetaList({
        pageNum: 1,
        pageSize: PAGE_SIZE_ALL,
      }).then((response) => {
        this.metaList = response.data.list;
        this.getMetaDetail();
      });
    },
    handleMetaTreeCheckChange(obj, isSelect) {
      // 判断当前节点是否已经在 selectedMetaList 中
      const index = this.selectedMetaList.findIndex(
        (item) => item.metaId === obj.id,
      );

      if (isSelect) {
        // 如果是选中且不存在于 selectedMetaList 中，则添加
        if (index === -1) {
          this.selectedMetaList.push({
            ...this.getSelectedObjFromMetaList(obj),
            metaId: obj.id,
          });
        }
      } else {
        // 如果是未选中且存在于 selectedMetaList 中，则删除
        if (index !== -1) {
          this.selectedMetaList.splice(index, 1);
        }
      }
    },
    handleDeleteMeta(index) {
      this.$refs.metaTreeRef.setChecked(
        this.selectedMetaList[index].metaId,
        false,
      );
    },
    handleSave() {
      this.$emit("finishCommit", this.selectedMetaList);
    },
  },
};
</script>

<style scoped lang="scss">
.app-container {
  box-sizing: border-box;
  height: calc((100vh - 50px) / 0.95);

  .row {
    height: 100%;
  }

  .card-wrap {
    height: 100%;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    /deep/ .el-card__body {
      flex: 1;
      overflow: auto;
    }
  }
}
</style>
